package com.ouc.openplatform.pampas;

import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.util.Assert;

public class SessionManagerImpl implements SessionManager, InitializingBean {
	private CacheManager cacheManager;
	private String cacheName = "session";

	public void setCacheManager(CacheManager cacheManager) {
		this.cacheManager = cacheManager;
	}

	public void setCacheName(String cacheName) {
		System.out.println("cacheName的值为" + cacheName);
		this.cacheName = cacheName;
	}

	@SuppressWarnings("unchecked")
	public Map<Object, Object> getSession(String sessionId) {
		Cache cache = getCache();
		Cache.ValueWrapper valueWrapper = cache.get(sessionId);
		if (valueWrapper == null) {
			Map<Object, Object> session = new HashMap<Object, Object>();
			session.put("_SESSION_CREATE_TIME_", Long.valueOf(System.currentTimeMillis()));
			addSession(sessionId, session);
			return session;
		}
		return (Map<Object, Object>) valueWrapper.get();
	}

	public void updateSession(String sessionId, Map<Object, Object> session) {
		Cache cache = getCache();
		cache.put(sessionId, session);
	}

	private Cache getCache() {
		Cache cache = this.cacheManager.getCache(this.cacheName);
		Assert.notNull(cache);
		return cache;
	}

	public void removeSession(String sessionId) {
		Cache cache = getCache();
		cache.evict(sessionId);
	}

	public void addSession(String id, Map<Object, Object> session) {
		Cache cache = getCache();
		cache.put(id, session);
	}

	public void afterPropertiesSet() throws Exception {
		Assert.notNull(this.cacheManager);
		Assert.notNull(this.cacheName);
		Assert.hasText(this.cacheName);
	}
}
